package com.shenhan.datasource.config;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.IntegerSerializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shenhan
 * @create 2020/9/8 11:08
 * @description
 */
@Configuration
public class KafkaProducerConfig {
    @Value("${kafka.bootstrap.servers}")
    private String bootstrapServers;
    @Value("${kafka.retries_config}")
    private String retriesConfig;
    @Value("${kafka.batch_size_config}")
    private String batchSize;
    @Value("${kafka.linger_ms_config}")
    private String lingerMs;
    @Value("${kafka.buffer_memory_config}")
    private String bufferMemory;

    @Bean
    public KafkaTemplate getKafkaTemplate() {
        Map<String, Object> configs = new HashMap<>();
        configs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        configs.put(ProducerConfig.RETRIES_CONFIG, retriesConfig);
        configs.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize);
        configs.put(ProducerConfig.LINGER_MS_CONFIG, lingerMs);
        configs.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory);
        //设置消息ky序列化类型  <Integer,String>
        configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
        configs.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        //自定义分区
        configs.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, CustomerPartitioner.class);
        DefaultKafkaProducerFactory defaultKafkaProducerFactory = new DefaultKafkaProducerFactory(configs);
        return new KafkaTemplate(defaultKafkaProducerFactory);
    }
}
